<template>
  <div>
    <Divider orientation="left">基本信息</Divider>
      <Form :model="param.paramProduct" :label-width="100" ref="productSupplyForm" class="modal_newuser_form">
      <Row>
        <Col span="12">
          <FormItem label="产品编码 :" prop="productCode" required>
            <Input v-model="param.paramProduct.productCode" class="form_step"></Input>
          </FormItem>
        </Col>
        <Col span="12">
          <FormItem label="尺码类型 :" prop="sysSizeType" inline >
            <Select v-model="param.paramProduct.sysSizeType" style="width:200px" >
              <Option v-for="item in sysSizeTypeDict" :value="item.value" :key="item.value">{{ item.name }}
              </Option>
            </Select>
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="8">
        <FormItem label="产品分类 :" required  prop="classificationIds">
          <div>
            <Button type="info" icon="ios-build" ghost @click="isclassificationTreeModelShowing=true">选择产品分类</Button>
          </div>
          <Col span="8"  v-for="(item,index) in classificationTreeShow" >
            <span class="tiy_key" style="text-align: left;font-size: 0.5em"  v-if="index<20||isShowAllCategories">{{item.level1}} /{{item.level2}}/{{item.level3}}</span>
          </Col>
          <div style="width: 100%;text-align: right;padding-right:9rem" v-if="classificationTreeShow.length>20">
            <Button type="dashed" size="small" @click="isShowAllCategories=!isShowAllCategories">{{isShowAllCategories?'点我折叠全部分类......':'点我查看分类列表......'}}</Button>
          </div>
        </FormItem>
      </Row>
    </Form>
    <Alert type="warning">不同色卡和规格的价格不一致时暂时无法抓取！</Alert>
    <Divider orientation="left">抓取信息</Divider>
    <Row>
      <span>抓取到的原始内容：</span>
      <Input type="textarea" placeholder="粘贴抓取到的数据" :autosize="{minRows: 5,maxRows: 10}"
             v-model.trim="data.carwlerData" @on-change="parseCrawledInfo" class="modal_form_input"></Input>
    </Row>
    <Row>
      <div v-if="status.modalAddByCrawler.isParsed">
        <Row>
          <div style="margin-top: 16px;">
            <Col span = "4"><label>标题：</label></Col>
            <Col span = "20"><label>{{param.crawler.title}}</label></Col>
          </div>
        </Row>
        <Row>
          <div style="margin-top: 16px;">
            <Col span = "6"><div>产品详情图：</div></Col>
            <Col span = "18">
              <div>
              <img v-for=" (item, index) in param.crawler.imgs" style="padding-left:5px;max-width:80px;" :src="item">
              </div>
            </Col>
          </div>
        </Row>
        <Row>
          <div style="margin-top: 16px;">
            <Col span = "6"><label>色卡：</label></Col>
            <Col span = "18">
              <List border size="large">
                <ListItem v-for=" (color, index) in param.crawler.colors">
                    <div style="margin-left: 26px;margin-right: 30px;"><ul>
                      <Strong>{{color.name}}</Strong>
                      <li v-for="(size) in color.sizes">
                        <label>{{size.name}} : {{size.stock}}; </label>
                      </li>
                    </ul></div>
                    <template slot="extra">
                      <img :src="color.image" style="max-width: 100px">
                    </template>
                </ListItem>
              </List>
            </Col>
          </div>
        </Row>
        <Row>
          <Col span = "6"><div style="margin-top: 16px;"><label>产品参数(勾选需要保存的参数)：</label></div></Col>
          <Col span = "18">
            <Table stripe border class="base_table" :columns="attrTable" :data="data.crawlerAttrs"
                   @on-selection-change="attrSelectedChanged"  no-data-text="暂无数据"></Table>
          </Col>
        </Row>
        <Row>
          <Col span="24" style="margin-top: 50px">
            <div style="text-align: center">
              <Button type="info" class="tiy_btn" @click="downloadPics" icon="ios-cloud-download-outline">打包下载图片</Button>
              <Button  class="tiy_btn"  @click="close">取消</Button>
              <Button type="primary" class="tiy_btn" @click="addProductByCrawler" >保存产品</Button>
            </div>
          </Col>
        </Row>
      </div>
    </Row>

    <!--产品分类选择-->
    <Modal :transfer=false v-model="isclassificationTreeModelShowing"
      title="选择产品所属的分类" >
      <div slot="footer"></div>
      <Tree :data="classificationTree" show-checkbox :multiple="true"
            ref="Tree"  @on-toggle-expand="toggleExpand"  @on-check-change="changeClassification"></Tree>
    </Modal>
  </div>
</template>

<!--javascript 代码-->
<script>
  import JSZip from "jszip"
  import FileSaver from "file-saver"
  import tiyData from "./js/crawler/crawler_data"
  import tiyAddEditData from "./js/list/add_edit_data"
  import {getProductCommonData} from "../js/commonUtils"

  import {
      addProductByCrawler,
      editProduct,
      initCrawledInfo
  } from  "./js/crawler/crawler_fun"

  export default {
    data(){
      return {
        data:tiyData.tData,
        sysSizeTypeDict: this.$store.getters.dictionaries.sysSizeTypeDict,//尺码类型
        param: tiyData.tParam,
        status: tiyData.tStatus,
        ruleProduct: tiyData.tStatus.rules,
          isclassificationTreeModelShowing :false,
          isShowAllCategories:false,
          classificationTreeShow:tiyData.tData.classificationTreeShow,
          classificationTree: tiyData.tData.classificationTree,//分类
          attrTable:tiyData.attrTable(this)
      }
    },
    methods: {
        close(){
            this.status.modalAddByCrawler.isShow = false;
            this.status.modalAddByCrawler.isParsed = false;
        },
        changeClassification(){
            tiyData.tData.classificationTreeShow.splice(0,tiyData.tData.classificationTreeShow.length);
            let level1 = this.$refs.Tree.getCheckedAndIndeterminateNodes().filter(item=>item.level==1);
            tiyData.tParam.paramProduct.classificationIds = [];
            this.$refs.Tree.getCheckedNodes().forEach(function(item){
                if(item.level==3){
                    tiyData.tParam.paramProduct.classificationIds.push(item.value);
                }
            })
            this.$refs.productSupplyForm.validateField('classificationIds');
            level1.forEach((item1)=>{
                item1.children.forEach((item2)=>{
                    if(item2.checked||item2.indeterminate){//2级分类选中或者半选
                        item2.children.forEach((item3)=>{//3级分类选中
                            if(item3.checked){
                                tiyData.tData.classificationTreeShow.push({'level1':item1.title,"level2":item2.title,"level3":item3.title});
                            }
                        });
                    }
                });
            });
        },
        toggleExpand(data){
            //展开分类，关闭同一级分类
            if(data.expand && data.level==1){
                tiyData.tData.classificationTree.forEach(function(item,index){
                    if(data.value!=item.value&&item.expand==true){
                        item.expand=false;
                        this.classificationTree.splice(index,1,item)
                    }
                });
            }
        },
        addProductByCrawler(){
            addProductByCrawler(this, tiyData);
        },
        toEditProduct(product){
            editProduct(this, product, tiyAddEditData);
        },
        parseCrawledInfo(){
            if(!this.data.carwlerData){
                initCrawledInfo(tiyData);
            } else {
                let parsed = this.$toJson(this.data.carwlerData);
                tiyData.tStatus.modalAddByCrawler.isParsed = true;
                tiyData.tParam.crawler.sourceUrl = parsed.sourceUrl;
                tiyData.tParam.crawler.title = parsed.title;
                tiyData.tParam.crawler.shippingFee = parsed.shippingFee;
                tiyData.tParam.crawler.colors = parsed.colors;
                tiyData.tParam.crawler.prices = parsed.prices;
                tiyData.tParam.crawler.imgs = parsed.imgs;
                tiyData.tData.crawlerAttrs = parsed.attrs;
            }
        },
        attrSelectedChanged(selection){
            tiyData.tParam.crawler.attrs.splice(0, tiyData.tParam.crawler.attrs.length);
            selection.forEach(function (item){
                let arg = {"name": item.name, "value":item.value};
                tiyData.tParam.crawler.attrs.push(arg);
            });
        },
        downloadPics(){ //打包下载抓取到的产品图片
            let title = '打包图片';
            let zip = new JSZip();
            let imgs = zip.folder(title);
            let colors = tiyData.tParam.crawler.colors; //色卡
            let productImgs = tiyData.tParam.crawler.imgs; //产品图列表

            if(!colors && !productImgs){
                this.$Modal.info({
                    title: "提示",
                    content: "没有需要下载的图片"
                });
                return;
            }

            let imageList = []; //需要下载的图片列表
            let nameList = []; //需要下载的图片名
            let extList = []; //下载图片的后缀
            if(productImgs){
                productImgs.forEach(function(img){
                    imageList.push(img);
                    let ext = img.substring(img.lastIndexOf(".") + 1);
                    extList.push(ext);
                    nameList.push(img.substring(img.lastIndexOf("/")+1));
                });
            }
            colors.forEach(function(color){
                let colorImage = color.image;
                if(!colorImage || imageList.includes(colorImage)){//没有色卡图或者色卡图如果和之前的产品图重复不再下载
                    return;
                }
                imageList.push(colorImage);
                let ext = colorImage.substring(colorImage.lastIndexOf(".") + 1);
                nameList.push(colorImage.substring(colorImage.lastIndexOf("/")+1));
                extList.push(ext);
            });

            let added = 0; //记录已经加载的图片
            imageList.forEach(function(imageUrl, index){
                let image = new Image();
                // 解决跨域 Canvas 污染问题
                image.setAttribute('crossOrigin', 'anonymous');
                image.src = imageUrl;

                image.onload = function () {
                    let canvas = document.createElement('canvas');
                    canvas.width = image.width;
                    canvas.height = image.height;

                    let context = canvas.getContext('2d');
                    context.drawImage(image, 0, 0, image.width, image.height);

                    let url = canvas.toDataURL(); // 得到图片的base64编码数据
                    canvas.toDataURL('image/' + extList[index]);

                    // 图片添加到压缩包里，需要去掉base64编码前的 data:image/ext;base64,
                    imgs.file(nameList[index], url.substring(22), {base64: true});

                    if (added++ === imageList.length - 1) { //最后一个文件生成下载的压缩文件。此处不能用index判断，因为异步请求返回顺序不确定。
                        zip.generateAsync({type: 'blob'}).then(function (content) {
                            FileSaver.saveAs(content, title + '.zip');
                        });
                    }
                };
            });

        }
    },
    components: {
    },
      mounted(){
          //产品导入查询分类和尺码
          let types = [];
          types.push(1);
          types.push(3);
          getProductCommonData(this, tiyData, types, false);
      }
  }
</script>

<!--css样式-->
<style lang="less" scoped>
@import  (once,optional)  "../css/base";

  .operation_item {
    text-align: left;
    margin-right: 20px;
  }

  .modal_newuser_form {
    padding-top: 30px;
    padding-bottom: 30px;
  }

  .modal_newuser_form_input {
    width: 200px;
    margin-right: 10px;
  }

  .form_step {
    width: 160px;
  }

  .modal_base_div {
    text-align: left;
    margin-top: 20px;
    padding: 20px;
    border: dotted thin #d1d1d1
  }

  .modal_base_div_title {
    text-align: left;
    margin-bottom: 10px
  }
  .color_modal{
    z-index:999999
  }

  .item_card{
    margin: 10px;
    text-align: center;
    /*border: solid #f1f1f1 1px;*/
    /*cursor: pointer;*/
    width: 100px;
  }

</style>
